﻿using System;
using System.IO;
using System.Web.UI.WebControls;

namespace CsharpHttpFileSharePage
{
    public partial class MyFileUpload : System.Web.UI.Page
    {
        /// <summary>
        /// Page_Load
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)//首次加载
            {
                AddListBox(string.Empty);
            }
        }

        /// <summary>
        /// 填充ListBox 并且定位于strFileName
        /// </summary>
        protected void AddListBox(string strFileName)
        {
            this.ListBox1.Items.Clear();
            string strPath = Server.MapPath("~/share_file/");

            // 检测指定目录是否存在
            if (Directory.Exists(strPath))
            {
                this.lblBasePath.Text = strPath;
            }
            else
            {
                lblMsg0.Text = "没有发现此文件夹：" + strPath;
                return;
            }

            //将指定文件夹中的文件保存到字符串数组中
            string[] name = Directory.GetFiles(strPath);
            foreach (string s in name)
            {
                FileInfo fi = new FileInfo(s);
                //将文件名添加到ListBox中
                ListItem listItem1 = new ListItem(fi.Name + " --> " + ZdsGetSimpSize(fi.Length), fi.Name);
                ListBox1.Items.Add(listItem1);

                //ListBox1.Items.Add(fi.Name + " --> " + ZdsGetSimpSize(fi.Length));
            }

            int iItemCount = this.ListBox1.Items.Count;
            if (iItemCount > 0)
            {
                if (string.IsNullOrEmpty(strFileName))
                {
                    ListBox1.SelectedIndex = 0;
                    //Session["txt"] = ZdsGetFirstStr(ListBox1.SelectedValue.ToString());
                    //this.hypLink1.Text = ZdsGetFirstStr(ListBox1.SelectedValue.ToString());
                    //this.hypLink1.NavigateUrl = "/share_file/" + this.hypLink1.Text;
                    this.hypLink1.Text = "";
                    this.hypLink1.NavigateUrl = "";
                }
                else
                {
                    //int iEndCount = this.ListBox1.Items.Count;
                    for (int iPos = 0; iPos < iItemCount; iPos++)
                    {
                        //string strTmp = ZdsGetFirstStr(this.ListBox1.Items[iPos].Value );
                        //strTmp = this.lblBasePath.Text + strTmp;
                        if (this.ListBox1.Items[iPos].Value == strFileName)
                        {
                            this.ListBox1.SelectedIndex = iPos;
                            //ListBox1.SelectedIndex = 0;
                            //Session["txt"] = ZdsGetFirstStr(ListBox1.SelectedValue.ToString());
                            this.hypLink1.Text = this.ListBox1.Items[iPos].Text;
                            this.hypLink1.NavigateUrl = "/share_file/" + this.ListBox1.Items[iPos].Value;
                            break;
                        }
                    }
                }


            }
        }

        /// <summary>
        /// 选择变化了ListBox1_SelectedIndexChanged
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Session["txt"] = ListBox1.SelectedValue.ToString();            
            //Session["txt"] = ZdsGetFirstStr(ListBox1.SelectedValue.ToString());
            this.hypLink1.Text = this.ListBox1.SelectedItem.Text; // ZdsGetFirstStr(ListBox1.SelectedValue.ToString());
            this.hypLink1.NavigateUrl = "/share_file/" + this.ListBox1.SelectedItem.Value;  //"/share_file/" + this.hypLink1.Text;
            this.lblMsg0.Text = "";
            this.lblMsg1.Text = "";
        }

        /// <summary>
        /// 设置下载链接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnSetDownFileLink_Click(object sender, EventArgs e)
        {
            if (this.ListBox1.Items.Count < 1)
            {
                return;
            }
            //判断是否选择文件名
            if (!string.IsNullOrEmpty(ListBox1.SelectedValue))
            {
                //if (Session["txt"] != null) 
                //if (!string.IsNullOrEmpty(this.hypLink1.Text))
                //{
                string strLinkFileName1 = this.ListBox1.SelectedValue;//ZdsGetFirstStr(ListBox1.SelectedValue);
                //获取文件路径
                //string path = Server.MapPath("share_file/") + Session["txt"].ToString();
                string path = this.lblBasePath.Text + strLinkFileName1;
                //初始化 FileInfo 类的实例，它作为文件路径的包装
                FileInfo fi = new FileInfo(path);

                //判断文件是否存在
                if (fi.Exists)
                {
                    string strFileNameExtensin = fi.Extension;
                    if (string.IsNullOrEmpty(strFileNameExtensin))
                    {
                        //压缩
                        //GZipCompress.Compress(fi);
                        string strZipedFile = fi.FullName + ".zip";
                        strLinkFileName1 = strLinkFileName1 + ".zip";

                        SharpZipLibHelper szh = new SharpZipLibHelper();
                        szh.ZipFile(fi.FullName, strZipedFile);
                        AddListBox(strLinkFileName1);
                    }
                    else
                    {
                        strFileNameExtensin = strFileNameExtensin.ToLower();
                        switch (strFileNameExtensin)
                        {
                            case ".rar":
                            case ".zip":
                            case ".gz":
                            case ".html":
                            case ".apk":
                                this.hypLink1.Text = strLinkFileName1;
                                this.hypLink1.NavigateUrl = "/share_file/" + strLinkFileName1;
                                break;
                            case ".md":                                
                                StreamReader sr1 = fi.OpenText();
                               string strMd= sr1.ReadToEnd();
                                //fi.CopyTo(fi.FullName + ".html");
                                using (StreamWriter sw = new StreamWriter( fi.FullName + ".html"))
                                {
                                    sw.WriteLine("<!doctype html><html lang = \"zh-CN\"><head><meta charset = \"utf-8\"><title>MD</title></head><body>");
                                    sw.WriteLine(strMd);
                                    sw.WriteLine("</body></html>");
                                }
                                strLinkFileName1 = strLinkFileName1 + ".html";
                                AddListBox(strLinkFileName1);
                                break;
                            default:
                                //压缩
                                //GZipCompress.Compress(fi);
                                string strZipedFile = fi.FullName + ".zip";
                                strLinkFileName1 = strLinkFileName1 + ".zip";

                                SharpZipLibHelper szh = new SharpZipLibHelper();
                                szh.ZipFile(fi.FullName, strZipedFile);
                                AddListBox(strLinkFileName1);
                                break;
                        }

                    }
                }
            }
            else
            {
                this.lblMsg1.Text = "请先选择需要下载的文件，谢谢！";
            }
        }

        /// <summary>
        /// 删除文件btnDeleteFile1_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnDeleteFile1_Click(object sender, EventArgs e)
        {
            this.lblMsg1.Text = "";
            if (this.ListBox1.Items.Count < 1)
            {
                return;
            }
            //判断是否选择文件名
            if (!string.IsNullOrEmpty(ListBox1.SelectedValue))
            {
                //if (Session["txt"] != null) 
                //if (!string.IsNullOrEmpty(this.hypLink1.Text))
                //{
                string strLinkFileName1 = this.ListBox1.SelectedValue;//ZdsGetFirstStr(ListBox1.SelectedValue);
                //获取文件路径
                //string path = Server.MapPath("share_file/") + Session["txt"].ToString();                    
                string path = this.lblBasePath.Text + strLinkFileName1;
                //初始化 FileInfo 类的实例，它作为文件路径的包装
                FileInfo fi = new FileInfo(path);

                //判断文件是否存在
                if (fi.Exists)
                {
                    //将文件删除
                    fi.Delete();
                    this.lblMsg1.Text = "删除的文件：" + fi.FullName;
                    AddListBox(string.Empty);
                }
            }
            else
            {
                this.lblMsg1.Text = "请先选择需要删除的文件，谢谢！";
            }
        }

        /// <summary>
        /// 上传文件btnFileUpLoad_Click
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        protected void BtnFileUpLoad_Click(object sender, EventArgs e)
        {
            if (this.aspFileUpload1.HasFile)
            {
                string filePath = this.lblBasePath.Text;  // Server.MapPath("~/share_file/");
                string fileName = this.aspFileUpload1.PostedFile.FileName;
                int intLength = fileName.Length;
                if (intLength > 1)
                {
                    int x = fileName.LastIndexOf('\\');
                    if (x > 0)
                    {
                        fileName = fileName.Substring(x + 1, intLength - x - 1);
                    }
                }

                this.aspFileUpload1.SaveAs(filePath + fileName);
                this.lblMsg1.Text = "\r\n<br />上传成功：" + filePath + fileName;
                //Response.Write("<p >上传成功!</p>");
                AddListBox(fileName);
            }
            else
            {
                this.lblMsg1.Text = "\r\n<br />请先选择文件!!!";
                //Response.Write("<p >请选择要上传的文件!</p>");
            }
        }

        /// <summary>
        /// 显示友好的文件大小ZdsGetSimpSize
        /// </summary>
        /// <param name="b">文件长度b</param>
        /// <returns>文件大小的字符串</returns>
        public static string ZdsGetSimpSize(long b)
        {
            const int GB = 1024 * 1024 * 1024;
            const int MB = 1024 * 1024;
            const int KB = 1024;


            if (b / GB >= 1)
            {
                return Math.Round(b / (float)GB, 2) + "GB";
            }


            if (b / MB >= 1)
            {
                return Math.Round(b / (float)MB, 2) + "MB";
            }


            if (b / KB >= 1)
            {
                return Math.Round(b / (float)KB, 2) + "KB";
            }


            return b + "B";
        }


    }


}
